package com.flashcash.solu.view.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.flashcash.kotlin.activity.MyActivityCenterActivity;
import com.flashcash.kotlin.activity.MyCouponActivity;
import com.flashcash.kotlin.activity.PolicyListActivity;
import com.flashcash.kotlin.activity.SnatchBotActivity;
import com.flashcash.kotlin.data.ActivityInfoBean;
import com.flashcash.kotlin.data.HelpCenterUrlAndHotlineBean;
import com.flashcash.kotlin.data.MeInfoBean;
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.solu.BuildConfig;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseFragment;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.utils.CommonUtils;
import com.flashcash.solu.view.certification.CertifyActivity;
import com.flashcash.solu.view.fragment.presenter.MeFraPreImp;
import com.flashcash.solu.view.fragment.presenter.MeFraPresenter;
import com.flashcash.solu.view.me.AboutActivity;
import com.flashcash.solu.view.me.HelpCenterActivity;
import com.flashcash.solu.view.me.MyInvitedInfoActivity;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.x.leo.rollview.OnItemClickListener;
import com.x.leo.rollview.RollView;
import com.x.leo.rollview.RollViewAdapter;

import java.util.ArrayList;

import butterknife.BindView;

import static com.flashcash.solu.widget.selfdefdialog.DialogManager.newDialog;

/**
 * Created by Miaoke on 2017/2/24.
 */

public class MeFragment extends BaseFragment<MeFraPresenter> implements View.OnClickListener, MeFraView {

    @BindView(R.id.id_textview_my_loan)
    TextView mIdTextviewMyLoan;
    @BindView(R.id.id_imagebutton_my_loan)
    ImageButton mIdImagebuttonMyLoan;
    @BindView(R.id.ll_myloan)
    LinearLayout mLlMyloan;
    @BindView(R.id.id_textview_pusat_kegiatan)
    TextView mPusat_Kegiatan;
    @BindView(R.id.id_imagebutton_security_setting)
    ImageButton mIdImagebuttonSecuritySetting;
    @BindView(R.id.ll_activity_center)
    LinearLayout mLlActivityCenter;
    @BindView(R.id.id_textview_help_center)
    TextView mIdTextviewHelpCenter;
    @BindView(R.id.id_imagebutton_help_center)
    ImageButton mIdImagebuttonHelpCenter;
    @BindView(R.id.ll_certification)
    LinearLayout mLlCertification;
    @BindView(R.id.ll_help)
    LinearLayout mLlHelp;
    @BindView(R.id.id_textview_about)
    TextView mIdTextviewAbout;
    @BindView(R.id.id_imagebutton_about)
    ImageButton mIdImagebuttonAbout;
    @BindView(R.id.ll_about)
    LinearLayout mLlAbout;
    @BindView(R.id.id_textview_customer_service_hotline)
    TextView mIdTextviewCustomerServiceHotline;
    @BindView(R.id.ll_hotline)
    LinearLayout mLlHotline;
    @BindView(R.id.sv_me)
    ScrollView mSvMe;
    @BindView(R.id.id_textview_online_service)
    TextView mOnlineService;
    @BindView(R.id.id_imagebutton_my_repayment_log)
    ImageButton mIdImagebuttonMyRepaymentLog;
    @BindView(R.id.ll_online_service_me)
    LinearLayout mllOnline_service;
    @BindView(R.id.tv_uername_me_fragment)
    TextView tvUsername;
    @BindView(R.id.tv_phone_number_me_fragment)
    TextView tvMobilePhone;
    @BindView(R.id.btn_login_out)
    TextView btnLogin;
    @BindView(R.id.ll_userspan_me_fragment)
    LinearLayout llUserSpan;
    @BindView(R.id.rv_me)
    RollView mHeaderRoller;
    @BindView(R.id.tv_num_kupon)
    TextView tvNumKupon;
    @BindView(R.id.ll_kupon)
    LinearLayout llKupon;
    @BindView(R.id.tv_num_undang_teman)
    TextView tvNumUndangTeman;
    @BindView(R.id.ll_undang_teman)
    LinearLayout llUndangTeman;
    @BindView(R.id.ll_policy)
    LinearLayout llPolicy;
    private RollViewAdapter mHeaderRollerAdapter;
    private ArrayList<String> mDatas;
    private ArrayList<ActivityInfoBean> dataBanner;
    private boolean doRefrash = false;
    private String hotLine = "";
    private String helpCenterUrl = "";

    @Override
    protected MeFraPresenter initPresenter() {
        return new MeFraPreImp();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_me;
    }


    @Override
    protected boolean doPreBuildHeader() {
        return true;
    }

    @Override
    protected boolean initHeader(TextView view) {
        view.setText(R.string.textview_me);
        return true;
    }

    @Override
    protected boolean showBack() {
        return false;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        RxBus.get().register(this);
//        llPolicy.setVisibility(View.VISIBLE);
        ((TextView) view.findViewById(R.id.tv_version)).setText("V" + BuildConfig.VERSION_NAME);

        mPresenter.getHelpCenterUrlAndHotline();

        mLlMyloan.setOnClickListener(this);
        mLlAbout.setOnClickListener(this);
        mLlHelp.setOnClickListener(this);
        mLlCertification.setOnClickListener(this);
        mLlHotline.setOnClickListener(this);
        mLlActivityCenter.setOnClickListener(this);
        mllOnline_service.setOnClickListener(this);
        llKupon.setOnClickListener(this);
        llUndangTeman.setOnClickListener(this);
//        llPolicy.setOnClickListener(this);
        mDatas = new ArrayList<>();
        mHeaderRollerAdapter = new RollViewAdapter<>(getContext(), mDatas);
        mHeaderRollerAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int index) {
//                if (dataBanner != null && dataBanner.size() > 0 &&
//                        index >= 0 && index < dataBanner.size()) {
//                    ActivityDetailAcivity.Companion.actionStart(MeFragment.this.getContext(), dataBanner.get(index));
//                }
            }
        });
        mHeaderRoller.setAdapter(mHeaderRollerAdapter);
        initNotLoginUserInfo();
    }

    @Override
    public void setHelpCenterUrlAndHotline(HelpCenterUrlAndHotlineBean data) {
        hotLine = data.getHotLine();
        helpCenterUrl = data.getHelpCenterUrl();

        if (!hotLine.isEmpty()) {
            mLlHotline.setVisibility(View.VISIBLE);
        }

        if (!helpCenterUrl.isEmpty()) {
            mLlHelp.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroyView() {
        RxBus.get().unregister(this);
        super.onDestroyView();
    }

    @Subscribe
    public void onLogout(EventCollection.LogoutEvent event) {
        initUserInfo(new MeInfoBean());
    }

    @Subscribe
    public void onLogIn(EventCollection.AccoutUpdateEvent event) {
        if (isVisible()) {
            mPresenter.initUserAccountInfo();
        } else {
            doRefrash = true;
        }
    }

    @Override
    protected void initData() {
        mPresenter.initUserAccountInfo();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && doRefrash) {
            doRefrash = false;
            mPresenter.initUserAccountInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isVisible() && doRefrash) {
            doRefrash = false;
            mPresenter.initUserAccountInfo();
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.ll_myloan:
//                mActivity.changeTo(new Intent(getContext(), MyLoanActivity.class), true);
//                break;
            case R.id.ll_online_service_me:
                if (!TokenManager.getInstance().hasLogin()) {
                    toLogin();
                    return;
                }
                startActivity(new Intent(getContext(), SnatchBotActivity.class));
                break;
            case R.id.ll_about:
                FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.ME_ABOUTUS, null);
                startActivity(new Intent(getContext(), AboutActivity.class));
                break;
            case R.id.ll_certification:
                //todo 跳转到认证页面
                FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.ME_CERTIFICATION, null);
                CertifyActivity.startCertifyActivity(getContext());
                break;
            case R.id.ll_help:
                FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.ME_HELPCENTER, null);
                Intent it = new Intent(getContext(), HelpCenterActivity.class);
                it.putExtra("helpCenterUrl", helpCenterUrl);
                startActivity(it);
                break;
            case R.id.ll_hotline:

                responseDisplay();

                break;
            case R.id.ll_activity_center:
                startActivity(new Intent(getContext(), MyActivityCenterActivity.class));
                break;
            case R.id.ll_undang_teman:
                Intent intent = new Intent(getContext(), MyInvitedInfoActivity.class);
                if (dataBanner != null && dataBanner.size() > 0 && dataBanner.get(0) != null) {
                    intent.putExtra(FieldParams.ACTIVITY_DETAIL_IMAGE_URL, dataBanner.get(0).getDetailUrl());
                }
                mActivity.changeTo(intent, true);
                break;
            case R.id.ll_kupon:
                MyCouponActivity.Companion.actionStart(getContext());
                break;
            case R.id.ll_policy:
                mActivity.changeTo(PolicyListActivity.class);
                break;
            default:
        }
    }

    private void showDialTips(String hotLine) {
        View view = View.inflate(getContext(), R.layout.dialog_hotline, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(
                (int) (getResources().getDisplayMetrics().widthPixels * 0.7f),
                (int) (getResources().getDisplayMetrics().heightPixels * 0.3f)
        ));
        final Dialog dialog = newDialog(getContext(), view, false);
        dialog.show();
        TextView text = (TextView) view.findViewById(R.id.tv_hotline_text);
        text.setText(String.format(getString(R.string.show_dial_hotline), hotLine));
        view.findViewById(R.id.btn_hotline_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        view.findViewById(R.id.btn_hotline_ensure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + hotLine);
                intent.setData(data);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initUserInfo(MeInfoBean data) {
        if (TokenManager.getInstance().hasLogin()) {
            tvUsername.setText(data.getName() + "");
            // TODO: 2019-05-09 要后台增加参数
            tvMobilePhone.setText(TokenManager.getInstance().getMobile());
            btnLogin.setText(R.string.button_logout);
            tvNumKupon.setText(data.getAvailableCouponCount() + "");
            tvNumUndangTeman.setText(data.getInviteeCount() + "");
            btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    doLogout();
                }
            });
        } else {
            initNotLoginUserInfo();
        }
        initRollAd(data);
    }

    private void initNotLoginUserInfo() {
        tvUsername.setText(R.string.button_login);
        tvMobilePhone.setText("");
        btnLogin.setText(R.string.button_login);
        tvNumKupon.setText("0");
        tvNumUndangTeman.setText("0");
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.login();
            }
        });
    }

    private void initRollAd(MeInfoBean data) {
        dataBanner = data.getBanner();
        if (dataBanner != null && dataBanner.size() > 0) {
            mDatas.clear();
            // dataBanner.add(0,new ActivityInfoBean("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503381298694&di=71cbfa592987f5a01d9f7fdaf37a72dc&imgtype=0&src=http%3A%2F%2Fi662.photobucket.com%2Falbums%2Fuu344%2FXS000%2Frtyheryiu46ti4o3toierutofgieruotgur.jpg"));
            for (ActivityInfoBean activityInfoBean : dataBanner) {
                //mDatas.add(activityInfoBean.getUrl());
                mDatas.add("http://flashcash.ph/image/me_banner.png");

            }
            mHeaderRollerAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean doLogout() {
        CommonUtils.showMessageDialog(getContext(), false, "Prompt", "Are you sure you want to log out", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_LOGOUT, null);
                mPresenter.logout();
            }
        });

        /*View view = View.inflate(getContext(), R.layout.dialog_question_for_result, null);
        final Dialog dialog = DialogManager.newDialog(getContext(), view, true);
        TextView tv_header = (TextView) view.findViewById(R.id.text_header);
        TextView tv_content = (TextView) view.findViewById(R.id.text_content);
        tv_content.setText(R.string.dialog_ensure_logout);
        tv_header.setText(R.string.button_logout);
        view.findViewById(R.id.ensure_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_LOGOUT, null);

                dialog.dismiss();
                mPresenter.logout();
            }
        });
        view.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });*/
        return false;
    }

    @Override
    public void responseDisplay() {
        showDialTips(hotLine);
    }

    @Override
    public void responseDisplayEmpty() {
        showDialTips(BuildConfig.HOTLINE);
    }
}